package br.com.gesclub.jsf.utils;

import java.util.logging.Logger;

import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;

import br.com.gesclub.business.exceptions.BusinessException;
import br.com.gesclub.system.exceptions.SystemException;

import com.sun.faces.application.ActionListenerImpl;
import com.sun.faces.util.FacesLogger;

/**
 * Responsável por capturar exceções que podem ocorrer em métodos Action e actionsListeners.
 *
 * @author Ellison
 */
public class ExceptionHandlerActionListener extends ActionListenerImpl {

    // Log instance for this class
    private static final Logger LOGGER = FacesLogger.APPLICATION.getLogger();

    @Override
    @SuppressWarnings("deprecation")
    public void processAction(ActionEvent event) throws AbortProcessingException {
        // Obtem o contexto JSF
        FacesContext context = FacesContext.getCurrentInstance();

        try {
            // Executa o método ActionListenerImpl
            super.processAction(event);

        } catch (FacesException e) {
            if (e.getCause() instanceof EvaluationException) {
                EvaluationException ee = (EvaluationException) e.getCause();

                if (ee.getCause() instanceof BusinessException) {
                    BusinessException be = (BusinessException) ee.getCause();

                    // Se um erro de regra de negócio mostra erro na tela
                    context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, be.getMessage(), null));
                } else if (ee.getCause() instanceof SystemException) {

                    // Redireciona para a pagina com o mapeamento 'erro' no faces-config.
                    context.getApplication().getNavigationHandler().handleNavigation(context, null, "erro");
                } else {
                    throw new FacesException(e);
                }
            }
        }
    }

}
